(function() {
    'use strict';

    angular.module('app.bookmark').controller('BookmarkController', BookmarkController);

    BookmarkController.$inject = ['$state', '$window', 'Bookmark', '$stateParams'];

    function BookmarkController($state, $window, Bookmark, $stateParams) {
        var vm = this;

        vm.bookmark = {};
        vm.bookmarks = [];
        vm.error = '';

        vm.create = function() {
            var bookmark = new Bookmark(vm.bookmark);

            bookmark.$save(function(response) {
                vm.bookmarks.unshift(response);
                vm.error = null;
            }, function(errorResponse) {
                vm.error = errorResponse.data.error;
            });
        };

        vm.remove = function(bookmark) {
            if ($window.confirm('Are you sure?')) {
                bookmark.$delete({
                    id: bookmark.id
                }, function(response) {
                    var filtered = vm.bookmarks.filter(function(element) {
                        return element.id !== bookmark.id;
                    });
                    vm.bookmarks = filtered;
                }, function(errorResponse) {
                    vm.error = errorResponse.data.error;
                });
            }
        };

        vm.view = function() {
            vm.bookmark = Bookmark.get({id: $stateParams.id});
        };

        vm.update = function() {
            var bookmark = vm.bookmark;
            bookmark.$update(function() {
                $state.go('bookmarks');
            }, function(errorResponse) {
                vm.error = errorResponse.data.error;
            });
        };

        vm.closeAlert = function() {
            vm.error = '';
        };

        vm.all = function() {
            vm.bookmarks = Bookmark.query();
        }
    }

}());
